<template>
  <div class="p-2">
    <!-- 添加或修改宿舍楼对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="buildingFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="宿舍楼名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入宿舍楼名称" />
        </el-form-item>
        <el-form-item label="宿舍楼类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择宿舍楼类型" style="width:100%">
            <el-option v-for="dict in buliding_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联闸机" prop="turnstiles">
          <el-select v-model="form.turnstiles" placeholder="请选择关联闸机" multiple style="width:100%" filterable>
            <el-option v-for="dict in zjDeviceList" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联摄像头" prop="cameras">
          <el-select v-model="form.cameras" placeholder="请选择关联摄像头" multiple style="width:100%" filterable>
            <el-option v-for="dict in sxtDeviceList" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="workers">
          <!-- <el-select v-model="form.workers" placeholder="请选择负责人" multiple style="width:100%" filterable>
            <el-option
              v-for="dict in sxtDeviceList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
              >{{ dict.name+' （'+dict.location+'）' }}</el-option
            >
          </el-select> -->
          <staff-select v-model="form.workers" multiple :style="{width:'100%'}"></staff-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Building" lang="ts">
import { listBuilding, getBuilding, delBuilding, addBuilding, updateBuilding } from '@/api/dormitory/building';
import { BuildingVO, BuildingQuery, BuildingForm } from '@/api/dormitory/building/types';
import { defineProps } from 'vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { buliding_type, use_status } = toRefs<any>(proxy?.useDict('buliding_type', 'use_status'));

const props = defineProps({
  nodeId: String || Number || undefined
});
const buildingList = ref<BuildingVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const buildingFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BuildingForm = {
  id: undefined,
  nodeId: undefined,
  name: undefined,
  type: undefined,
  code: undefined,
  orderNum: undefined,
  turnstiles: undefined,
  turnstilesText: undefined,
  cameras: undefined,
  cameraText: undefined,
  workers: undefined,
  workerText: undefined,
  floorCount: undefined,
  roomCount: undefined,
  roomMemberCount: undefined,
  remark: undefined,
  status: undefined
};
const data = reactive<PageData<BuildingForm, BuildingQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nodeId: undefined,
    name: undefined,
    type: undefined,
    code: undefined,
    orderNum: undefined,
    turnstiles: undefined,
    turnstilesText: undefined,
    cameras: undefined,
    cameraText: undefined,
    workers: undefined,
    workerText: undefined,
    floorCount: undefined,
    roomCount: undefined,
    roomMemberCount: undefined,
    params: {
      createTime: undefined
    }
  },
  rules: {
    name: [{ required: true, message: '宿舍楼名称不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
    cameras: [{ required: true, message: '关联摄像头不能为空', trigger: 'blur' }],
    workers: [{ required: true, message: '负责人不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询宿舍楼列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  const res = await listBuilding(queryParams.value);
  buildingList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  buildingFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: BuildingVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加宿舍楼';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();
  const _id = row?.sourceId || ids.value[0];
  const res = await getBuilding(_id);
  res.data['cameras'] = res.data.cameras ? res.data.cameras?.split(',') : [];
  res.data['workers'] = res.data.workers ? res.data.workers?.split(',') : [];
  res.data['turnstiles'] = res.data.turnstiles ? res.data.turnstiles?.split(',') : [];
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改宿舍楼';
};

const emit = defineEmits(['onSuccess']);

/** 提交按钮 */
const submitForm = () => {
  buildingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      let params = {
        ...form.value,
        cameras: form.value.cameras?.join(','),
        turnstiles: form.value.turnstiles?.join(','),
        workers: form.value.workers?.join(',')
      };
      let tipText = '修改成功';
      if (form.value.id) {
        await updateBuilding(params).finally(() => (buttonLoading.value = false));
      } else {
        tipText = '新增成功';
        params.nodeId = props.nodeId;
        await addBuilding(params).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess(tipText);
      dialog.visible = false;
      emit('onSuccess');
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const _ids = row?.sourceId || ids.value;
  await proxy?.$modal.confirm('是否确认删除"' + row?.name + '"？').finally(() => (loading.value = false));
  await delBuilding(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  emit('onSuccess');
};

import { DeviceInfoQuery, DeviceInfoVO } from '@/api/device/deviceInfo/types';
import { listDeviceInfo } from '@/api/device/deviceInfo';
const deviceQueryParams = reactive<DeviceInfoQuery>({
  pageNum: 1,
  pageSize: 10000,
  parentId: undefined,
  type: 1,
  name: undefined,
  series: undefined,
  ip: undefined,
  deviceCode: undefined,
  guid: undefined,
  area: undefined,
  location: undefined,
  position: undefined,
  onlineStatus: undefined,
  offlineTime: undefined,
  status: 1
});
const zjDeviceList = ref<any>([]);
const sxtDeviceList = ref<any>([]);
const getDeviceInfoList = async (type: number) => {
  deviceQueryParams.type = type;
  const res = await listDeviceInfo(deviceQueryParams);
  return res.rows;
};

defineExpose({
  handleAdd,
  handleUpdate,
  handleDelete
});

onMounted(() => {
  getDeviceInfoList(0).then((res) => {
    zjDeviceList.value = res;
  });
  getDeviceInfoList('1,4').then((res) => {
    sxtDeviceList.value = res;
  });
});
</script>
